package com.fastjars.business.shiro.realms;

import com.fastjars.business.shiro.token.BaseToken;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * ModularRealmAuthenticator
 * 多Realm选着认证
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2017/12/23
 * @version 1.0.0
 */
public class ModularRealmAuthenticator extends org.apache.shiro.authc.pam.ModularRealmAuthenticator{

    public static final Logger LOGGER = LoggerFactory.getLogger(ModularRealmAuthenticator.class);

    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        AuthenticationStrategy strategy = getAuthenticationStrategy();
        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
        for (Realm realm : realms) {
            BaseToken baseToken = (BaseToken) token;
            if(realm.getClass() != BaseToken.TOKEN_TYPE.get(baseToken.getRealmType())){
                continue;
            }
            aggregate = strategy.beforeAttempt(realm, token, aggregate);
            if (realm.supports(token)) {
                AuthenticationInfo info = null;
                Throwable t = null;
                try {
                    info = realm.getAuthenticationInfo(token);
                } catch (Throwable throwable) {
                    throw throwable;
                }
                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
                if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
                    LOGGER.debug("aggregate："+aggregate.toString());
                    return aggregate;
                }
            } else {
                LOGGER.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
            }
        }
        aggregate = strategy.afterAllAttempts(token, aggregate);
        return aggregate;
    }
}
